package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"new/models"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

type NewController struct {
	beego.Controller
}
type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *NewController) Ask() {

	title := c.GetString("title")
	content := c.GetString("content")
	img := c.GetString("img")
	state := c.GetString("state")
	cateId, _ := c.GetInt("cateId")
	asknew := models.New{

		Title:   title,
		Content: content,
		Img:     img,
		CateId:  uint(cateId),
		State:   state,
	}
	err := models.DB.Debug().Create(&asknew).Error

	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "发布失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {

		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "发布成功",
			Data: nil,
		}
		c.ServeJSON()

	}
}
func (c *NewController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "请选择上传的文件",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close()

	//PNG、JPEG、JPG
	ext := map[string]bool{
		".jpg":  true,
		".jpeg": true,
		".png":  true,
	}
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	if !ext[suffix] {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "文件格式错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if header.Size > 2*1024*1024 {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "上传的文件过大",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "文件上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		imgSrc := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "文件上传成功",
			Data: imgSrc,
		}
		c.ServeJSON()

	}

}
func (c *NewController) NewType() {
	var news []models.NewType
	err := models.DB.Find(&news).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "分类查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "分类查询成功",
			Data: news,
		}
		c.ServeJSON()
	}
}

func (c *NewController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 3)
	title := c.GetString("title")
	pageData := make(map[string]interface{})
	key := "page:" + strconv.Itoa(page) + ":" + title
	val, err := models.RedisDB.Get(key).Result()
	if err != nil {
		query := models.DB.Model(&models.New{})
		if title != "" {
			query.Where("title like ?", "%"+title+"%")
		}
		var count int64
		query.Count(&count)
		offset := (page - 1) * size
		var allnew []models.New
		err = query.Preload("NewType").Offset(offset).Limit(size).Find(&allnew).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 0,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return

		} else {
			pageData["count"] = count
			pageData["allnew"] = allnew
			jsonByte, _ := json.Marshal(&pageData)
			value := string(jsonByte)
			models.RedisDB.Set(key, value, time.Minute*2)
			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "查询成功-mysql",
				Data: pageData,
			}
			c.ServeJSON()

		}

	} else {
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功-redis",
			Data: pageData,
		}
		c.ServeJSON()

	}

}

func (c *NewController) Info() {
	id, _ := c.GetInt("id")
	var info models.New
	//title := c.GetString("title")
	key := "id:" + strconv.Itoa(id)
	keys := "Rank"
	val, err := models.RedisDB.Get(key).Result()

	if err != nil {
		err = models.DB.Preload("NewType").Where("id=?", id).First(&info).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 0,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			jsonByte, _ := json.Marshal(&info)
			value := string(jsonByte)
			models.RedisDB.Set(key, value, time.Minute*2)
			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "查询成功-mysql",
				Data: info,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &info)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功-redis",
			Data: info,
		}
		c.ServeJSON()
	}
	models.RedisDB.ZIncrBy(keys, 1, info.Title)

}
func (c *NewController) Del() {
	id, _ := c.GetInt("id")
	var allnew models.New
	state := c.GetString("state")
	err := models.DB.Preload("NewType").Where("state=?", "已发布").First(&allnew).Error

	if state != "" {
		res := JsonR{
			Code: 0,
			Msg:  "禁止删除已发布新闻",
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	err = models.DB.Debug().Delete(&models.New{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {

		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()

	}
}
func (c *NewController) Update() {
	id, _ := c.GetInt("id")
	title := c.GetString("title")
	img := c.GetString("img")
	state := c.GetString("state")
	cateId, _ := c.GetInt("cateId")
	asknew := models.New{

		Title:  title,
		Img:    img,
		CateId: uint(cateId),
		State:  state,
	}
	err := models.DB.Debug().Where("id=?", id).Updates(&asknew).Error

	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {

		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()

	}
}

func (c *NewController) Comment() {
	content := c.GetString("content")
	newId, _ := c.GetInt("newId")
	userId, _ := c.GetInt("userId")
	if userId == 0 {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "用户不登录不能评论",
			Data: nil,
		}
	}
	commit := models.Commit{

		Content: content,
		NewId:   uint(newId),
		UserId:  uint(userId),
	}
	err := models.DB.Create(&commit).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "评论失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "评论成功",
			Data: nil,
		}
		c.ServeJSON()

	}
}

// 收藏
func (c *NewController) Collection() {

	newId, _ := c.GetInt("newId")
	userId, _ := c.GetInt("userId")
	if userId == 0 {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "用户不登录不能收藏",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	commit := models.Collection{

		NewId:  uint(newId),
		UserId: uint(userId),
	}
	err := models.DB.Create(&commit).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "收藏失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "收藏成功",
			Data: nil,
		}
		c.ServeJSON()

	}
}

// 收藏列表
func (c *NewController) CollectList() {
	//.Preload("NewType")
	var collectlist []models.Collection
	err := models.DB.Preload("New").Preload("User").Find(&collectlist).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "收藏查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "收藏查询成功",
			Data: collectlist,
		}
		c.ServeJSON()

	}
}

func (c *NewController) Rank() {
	keys := "Rank"
	str, err := models.RedisDB.ZRevRangeWithScores(keys, 0, -1).Result()
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "排行榜失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "排行榜成功",
			Data: str,
		}
		c.ServeJSON()

	}
}
